﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.MaterialManagements;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.MaterialManagements
{
    /// <summary>
    /// 物料管理添加Handler
    /// </summary>
    public class CreateMaterialManagementHandler : IRequestHandler<CreateMaterialManagementCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物料管理表仓储
        /// </summary>
        public readonly IBaseRepository<MaterialManagement> materialManagementrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateMaterialManagementHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="materialManagementrepository"></param>
        /// <param name="logger"></param>
        public CreateMaterialManagementHandler(IMapper mapper, IBaseRepository<MaterialManagement> materialManagementrepository, ILogger<CreateMaterialManagementHandler> logger)
        {
            this.mapper = mapper;
            this.materialManagementrepository = materialManagementrepository;
            this.logger = logger;
        }
        /// <summary>
        /// 物料管理添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(CreateMaterialManagementCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                MaterialManagement management = mapper.Map<MaterialManagement>(request);
                var res = await materialManagementrepository.Add(management);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = res;
                    result.Msg = "物料管理添加成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "物料管理添加失败" + ex.Message;
                logger.LogError("物料管理添加失败" + ex.Message);
            }
            return result;
        }
    }
}
